﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices; //调用WINDOWS API函数时要用到
using Microsoft.Win32; //写入注册表时要用到
using System.Threading;
using System.Media;

namespace EMT
{
    static class Program
    {
        static int sWidth = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Width;
        static int sHeight = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Height;
        public static int time_delay = 100;//输入后延时
        public static bool addQ = true;//是否追加Q
        public static bool flag_writting = false;//打字模式
        public static bool flag_model = false;//两种连招
        public static bool model2_switch = false;//连招2模式下半段连招标记
        public static Thread thread ;
        static Dictionary<string, SoundPlayer> sDic = new Dictionary<string, SoundPlayer>();//音乐资源字典

        //用于计算锁定视角下W落点坐标的辅助数据
        public static int xW1 = 0;//锁定视角下第一个和第三个W的坐标
        public static int yW1 = 0;//锁定视角下第一个和第三个W的坐标
        public static int xW2 = 0;//锁定视角下第二个和第四个W的坐标
        public static int yW2 = 0;//锁定视角下第二个和第四个W的坐标
        public static int x0 = 0;//锁定视角下自己的坐标
        public static int y0 = 0;//锁定视角下自己的坐标
       
        //用于计算第三个W和第四个W落点坐标的辅助数据
        public static int x1 = 0;//第一个W的坐标
        public static int y1 = 0;//第一个W的坐标
        public static int x2 = 0;//第二个W的坐标
        public static int y2 = 0;//第二个W的坐标
        public static double distance = 0;//第一个与第二个W间的距离 
        public static double cos = 0;//余弦值 
        public static double sin = 0;//正弦值 


        private static void hook_KeyDown(object sender, KeyEventArgs e)
        {
            //范例：
            //模拟键盘：keybd_event((byte)Keys.W, 0, 0, 0);
            //          keybd_event((byte)Keys.W, 0, 2, 0);
            //鼠标定位：MouseHelper.SetCursorPos(0, 0);
            //鼠标点击：MouseHelper.mouse_event(MouseHelper.MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0);
            //          MouseHelper.mouse_event(MouseHelper.MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
            //获取屏幕高宽：int xWidth = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Width;
            //              int yHeight = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Height;

            //1920*1080 屏幕宽高参数
            //"~"键的键值：Keys.Oemtilde 

            //切换打字模式
            if(e.KeyValue == (int)Keys.F1)
            {
                if (flag_writting)
                {flag_writting = false;}
                else
                {flag_writting = true;}
            }
            //打字模式下不出发jio本
            if (flag_writting)
            {return;}

            switch (e.KeyValue)
            {
                case (int)Keys.T:
                     thread = new Thread(lianzhao);
                    thread.Start();
                    break;

                case (int)Keys.Oemtilde:
                    
                    switchLianzhao();
                    break;

                case (int)Keys.X:
                    switchQ();
                    break;

            }

        }

        //使用连招
        public static void lianzhao()
        {
            //判断是使用连招1还是连招2
            if (flag_model)
            {
                lianzhao1();
            }
            else
            {
                lianzhao2();
            }
        }

        //连招1
        public static void lianzhao1() {
            keybd_event((byte)Keys.W, 0, 0, 0);
            keybd_event((byte)Keys.W, 0, 2, 0);

            xW2 = Control.MousePosition.X;
            yW2 = Control.MousePosition.Y;
            xW1 = Convert.ToInt32(0.45 * xW2 + 0.55 * x0);
            yW1 = Convert.ToInt32(0.45 * yW2 + 0.55 * y0);
            MouseHelper.SetCursorPos(xW1, yW1);
            Thread.Sleep(time_delay);
            keybd_event((byte)Keys.W, 0, 0, 0);
            keybd_event((byte)Keys.W, 0, 2, 0);
            Thread.Sleep(50);
            keybd_event((byte)Keys.E, 0, 0, 0);
            keybd_event((byte)Keys.E, 0, 2, 0);



            MouseHelper.SetCursorPos(xW2, yW2);
            Thread.Sleep(time_delay);
            keybd_event((byte)Keys.W, 0, 0, 0);
            keybd_event((byte)Keys.W, 0, 2, 0);

            MouseHelper.SetCursorPos(xW1, yW1);
            Thread.Sleep(500);
            keybd_event((byte)Keys.W, 0, 0, 0);
            keybd_event((byte)Keys.W, 0, 2, 0);

            MouseHelper.SetCursorPos(xW2, yW2);
            Thread.Sleep(400);
            keybd_event((byte)Keys.W, 0, 0, 0);
            keybd_event((byte)Keys.W, 0, 2, 0);
            Thread.Sleep(time_delay);
            if (addQ)
            {
                keybd_event((byte)Keys.Q, 0, 0, 0);
                keybd_event((byte)Keys.Q, 0, 2, 0);
            }
        }

        //连招2
        public static void lianzhao2()
        {
            //判断使用连招2的上半段还是下半段
            if (!model2_switch)
            {
                keybd_event((byte)Keys.W, 0, 0, 0);
                keybd_event((byte)Keys.W, 0, 2, 0);
                Thread.Sleep(time_delay);

                x1 = Control.MousePosition.X;
                y1 = Control.MousePosition.Y; 
                keybd_event((byte)Keys.W, 0, 0, 0);
                keybd_event((byte)Keys.W, 0, 2, 0);
                Thread.Sleep(50);
                keybd_event((byte)Keys.E, 0, 0, 0);
                keybd_event((byte)Keys.E, 0, 2, 0);
                model2_switch = true;
            }
            else
            {
                Thread.Sleep(time_delay);
                x2 = Control.MousePosition.X;
                y2 = Control.MousePosition.Y;
                distance = Math.Sqrt(Math.Pow(y2 - y1, 2) + Math.Pow(x2 - x1, 2));
                if (distance <= 0) { distance = 100; } //防止在计算cos和sin时除数为零 引发异常
                cos = (x2 - x1) / distance;
                sin = (y2 - y1) / distance;
                keybd_event((byte)Keys.W, 0, 0, 0);
                keybd_event((byte)Keys.W, 0, 2, 0);

                MouseHelper.SetCursorPos(x2 + Convert.ToInt32(80 * sin), y2 - Convert.ToInt32(80 * cos));
                Thread.Sleep(time_delay);
                keybd_event((byte)Keys.W, 0, 0, 0);
                keybd_event((byte)Keys.W, 0, 2, 0);

                
                MouseHelper.SetCursorPos(x2 - Convert.ToInt32(80 * sin), y2 + Convert.ToInt32(80 * cos));
                Thread.Sleep(time_delay);
                keybd_event((byte)Keys.W, 0, 0, 0);
                keybd_event((byte)Keys.W, 0, 2, 0);
                model2_switch = false;

                Thread.Sleep(time_delay);
                if (addQ)
                {
                    keybd_event((byte)Keys.Q, 0, 0, 0);
                    keybd_event((byte)Keys.Q, 0, 2, 0);
                }
            }
        }

        //切换连招模式
        public static void switchLianzhao()
        {

            if (flag_model)
            {
                flag_model = false;
                model2_switch = false;
                //语音
                sDic["combo2"].Play();
            }
            else
            {
                flag_model = true;
                //语音
                sDic["combo1"].Play();
            }
        }

        //切换是否追加Q
        public static void switchQ() {
            if (addQ)
            {
                addQ = false;
                //语音
                sDic["Q_off"].Play();
            }
            else
            {
                addQ = true;
                //语音
                sDic["Q_on"].Play();
            }
        }

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {

            KeyboardHook k_hook = new KeyboardHook();
            k_hook.KeyDownEvent += new KeyEventHandler(hook_KeyDown);//钩住键按下 
            k_hook.Start();//安装键盘钩子

            init();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());


        }

        private static void init()
        {
            //加载音频文件
            string[] s = new string[6] { "combo1", "combo2", "scope_large", "scope_mini", "Q_on", "Q_off" };
            int i = 0;
            for (; i < s.Length; i++)
            {
                SoundPlayer player = new SoundPlayer();
                player.SoundLocation = s[i] + ".wav";
                player.Load();
                sDic.Add(s[i], player);
            }

            //确定屏幕中心坐标（即锁定视角下自己的坐标）
            x0 = sWidth / 2;
            y0 = (sHeight - 40) / 2;
            
        }

        /// <summary>
        /// 模拟键盘点击的方法，这个比sendKey方法更快响应
        /// </summary>
        /// <param name="bVk"></param>
        /// <param name="bScan"></param>
        /// <param name="dwFlags"></param>
        /// <param name="dwExtraInfo"></param>
        [DllImport("user32.dll")]
        public static extern void keybd_event(
                    byte bVk,    //虚拟键值
                    byte bScan,// 一般为0
                    int dwFlags,  //这里是整数类型  0 为按下，2为释放
                    int dwExtraInfo  //这里是整数类型 一般情况下设成为 0
                );
    }

    /// <summary>
    /// 鼠标钩子/// </summary>
    class MouseHelper
    {
        [System.Runtime.InteropServices.DllImport("user32")]
        public static extern int mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
        //移动鼠标 
        public const int MOUSEEVENTF_MOVE = 0x0001;
        //模拟鼠标左键按下 
        public const int MOUSEEVENTF_LEFTDOWN = 0x0002;
        //模拟鼠标左键抬起 
        public const int MOUSEEVENTF_LEFTUP = 0x0004;
        //模拟鼠标右键按下 
        public const int MOUSEEVENTF_RIGHTDOWN = 0x0008;
        //模拟鼠标右键抬起 
        public const int MOUSEEVENTF_RIGHTUP = 0x0010;
        //模拟鼠标中键按下 
        public const int MOUSEEVENTF_MIDDLEDOWN = 0x0020;
        //模拟鼠标中键抬起 
        public const int MOUSEEVENTF_MIDDLEUP = 0x0040;
        //标示是否采用绝对坐标 
        public const int MOUSEEVENTF_ABSOLUTE = 0x8000;
        [DllImport("user32.dll")]
        public static extern bool SetCursorPos(int X, int Y);
    }

    /// <summary>
    /// 键盘钩子/// </summary>
    class KeyboardHook
        {
            public event KeyEventHandler KeyDownEvent;
            public event KeyPressEventHandler KeyPressEvent;
            public event KeyEventHandler KeyUpEvent;

            public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
            static int hKeyboardHook = 0; //声明键盘钩子处理的初始值
                                          //值在Microsoft SDK的Winuser.h里查询
                                          // http://www.bianceng.cn/Programming/csharp/201410/45484.htm
            public const int WH_KEYBOARD_LL = 13;   //线程键盘钩子监听鼠标消息设为2，全局键盘监听鼠标消息设为13
            HookProc KeyboardHookProcedure; //声明KeyboardHookProcedure作为HookProc类型
                                            //键盘结构
            [StructLayout(LayoutKind.Sequential)]
            public class KeyboardHookStruct
            {
                public int vkCode;  //定一个虚拟键码。该代码必须有一个价值的范围1至254
                public int scanCode; // 指定的硬件扫描码的关键
                public int flags;  // 键标志
                public int time; // 指定的时间戳记的这个讯息
                public int dwExtraInfo; // 指定额外信息相关的信息
            }
            //使用此功能，安装了一个钩子
            [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
            public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);


            //调用此函数卸载钩子
            [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
            public static extern bool UnhookWindowsHookEx(int idHook);


            //使用此功能，通过信息钩子继续下一个钩子
            [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
            public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);

            // 取得当前线程编号（线程钩子需要用到）
            [DllImport("kernel32.dll")]
            static extern int GetCurrentThreadId();

            //使用WINDOWS API函数代替获取当前实例的函数,防止钩子失效
            [DllImport("kernel32.dll")]
            public static extern IntPtr GetModuleHandle(string name);

            public void Start()
            {
                // 安装键盘钩子
                if (hKeyboardHook == 0)
                {
                    KeyboardHookProcedure = new HookProc(KeyboardHookProc);
                    hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProcedure, GetModuleHandle(System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName), 0);
                    //hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProcedure, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
                    //************************************
                    //键盘线程钩子
                    //SetWindowsHookEx( 2,KeyboardHookProcedure, IntPtr.Zero, GetCurrentThreadId());//指定要监听的线程idGetCurrentThreadId(),
                    //键盘全局钩子,需要引用空间(using System.Reflection;)
                    //SetWindowsHookEx( 13,MouseHookProcedure,Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]),0);
                    //
                    //关于SetWindowsHookEx (int idHook, HookProc lpfn, IntPtr hInstance, int threadId)函数将钩子加入到钩子链表中，说明一下四个参数：
                    //idHook 钩子类型，即确定钩子监听何种消息，上面的代码中设为2，即监听键盘消息并且是线程钩子，如果是全局钩子监听键盘消息应设为13，
                    //线程钩子监听鼠标消息设为7，全局钩子监听鼠标消息设为14。lpfn 钩子子程的地址指针。如果dwThreadId参数为0 或是一个由别的进程创建的
                    //线程的标识，lpfn必须指向DLL中的钩子子程。 除此以外，lpfn可以指向当前进程的一段钩子子程代码。钩子函数的入口地址，当钩子钩到任何
                    //消息后便调用这个函数。hInstance应用程序实例的句柄。标识包含lpfn所指的子程的DLL。如果threadId 标识当前进程创建的一个线程，而且子
                    //程代码位于当前进程，hInstance必须为NULL。可以很简单的设定其为本应用程序的实例句柄。threaded 与安装的钩子子程相关联的线程的标识符
                    //如果为0，钩子子程与所有的线程关联，即为全局钩子
                    //************************************
                    //如果SetWindowsHookEx失败
                    if (hKeyboardHook == 0)
                    {
                        Stop();
                        throw new Exception("安装键盘钩子失败");
                    }
                }
            }
            public void Stop()
            {
                bool retKeyboard = true;


                if (hKeyboardHook != 0)
                {
                    retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
                    hKeyboardHook = 0;
                }

                if (!(retKeyboard)) throw new Exception("卸载钩子失败！");
            }
            //ToAscii职能的转换指定的虚拟键码和键盘状态的相应字符或字符
            [DllImport("user32")]
            public static extern int ToAscii(int uVirtKey, //[in] 指定虚拟关键代码进行翻译。
                                             int uScanCode, // [in] 指定的硬件扫描码的关键须翻译成英文。高阶位的这个值设定的关键，如果是（不压）
                                             byte[] lpbKeyState, // [in] 指针，以256字节数组，包含当前键盘的状态。每个元素（字节）的数组包含状态的一个关键。如果高阶位的字节是一套，关键是下跌（按下）。在低比特，如果设置表明，关键是对切换。在此功能，只有肘位的CAPS LOCK键是相关的。在切换状态的NUM个锁和滚动锁定键被忽略。
                                             byte[] lpwTransKey, // [out] 指针的缓冲区收到翻译字符或字符。
                                             int fuState); // [in] Specifies whether a menu is active. This parameter must be 1 if a menu is active, or 0 otherwise.

            //获取按键的状态
            [DllImport("user32")]
            public static extern int GetKeyboardState(byte[] pbKeyState);


            [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
            private static extern short GetKeyState(int vKey);

            private const int WM_KEYDOWN = 0x100;//KEYDOWN
            private const int WM_KEYUP = 0x101;//KEYUP
            private const int WM_SYSKEYDOWN = 0x104;//SYSKEYDOWN
            private const int WM_SYSKEYUP = 0x105;//SYSKEYUP

            private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
            {
                // 侦听键盘事件
                if ((nCode >= 0) && (KeyDownEvent != null || KeyUpEvent != null || KeyPressEvent != null))
                {
                    KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
                    // raise KeyDown
                    if (KeyDownEvent != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))
                    {
                        Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
                        KeyEventArgs e = new KeyEventArgs(keyData);
                        KeyDownEvent(this, e);
                    }

                    //键盘按下
                    if (KeyPressEvent != null && wParam == WM_KEYDOWN)
                    {
                        byte[] keyState = new byte[256];
                        GetKeyboardState(keyState);

                        byte[] inBuffer = new byte[2];
                        if (ToAscii(MyKeyboardHookStruct.vkCode, MyKeyboardHookStruct.scanCode, keyState, inBuffer, MyKeyboardHookStruct.flags) == 1)
                        {
                            KeyPressEventArgs e = new KeyPressEventArgs((char)inBuffer[0]);
                            KeyPressEvent(this, e);
                        }
                    }

                    // 键盘抬起
                    if (KeyUpEvent != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP))
                    {
                        Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
                        KeyEventArgs e = new KeyEventArgs(keyData);
                        KeyUpEvent(this, e);
                    }

                }
                //如果返回1，则结束消息，这个消息到此为止，不再传递。
                //如果返回0或调用CallNextHookEx函数则消息出了这个钩子继续往下传递，也就是传给消息真正的接受者
                return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
            }
            ~KeyboardHook()
            {
                Stop();
            }
        }
    
}
